﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using InvoiceInvoker.Logic;

namespace InvoiceInvoker.MvcUI.Filters
{
	public class InvoicesFilter
	{
		[DisplayName("Status")]
		public string Status { get; set; }

		[DisplayName("Wystawiona od")]
		public DateTime MinDate { get; set; }

		[DisplayName("Wystawiona do")]
		public DateTime MaxDate { get; set; }

		[DisplayName("Klient")]
		public string Customer { get; set; }

		[DisplayName("Produkty")]
		public string ProductNames { get; set; }

		[DisplayName("Min. wartość")]
		[RegularExpression("^[0-9]+(,[0-9])?[0-9]*$")]
		public string MinValue { get; set; }

		[DisplayName("Maks. wartość")]
		[RegularExpression("^[0-9]+(,[0-9])?[0-9]*$")]
		public string MaxValue { get; set; }

		public InvoicesFilter()
		{
			Status = Invoice.InvoiceStatus.Created.ToString();
			MinDate = new DateTime(0);
			MaxDate = DateTime.Today;
		}

		public Func<Invoice, bool> GetExpression()
		{
			string customer = Customer ?? "";
			string products = ProductNames ?? "";
			decimal minValue;
			decimal maxValue;

			string[] separator = { ", ", "," };
			List<string> productNames = products.ToLower().Split(separator, StringSplitOptions.RemoveEmptyEntries).ToList();

			decimal.TryParse(MinValue, out minValue);

			if (decimal.TryParse(MaxValue, out maxValue) == false)
				maxValue = decimal.MaxValue;

			return invoice =>
				invoice.Status == Status
				&&
				invoice.CreationDate >= MinDate && invoice.CreationDate <= MaxDate
				&&
				(
				invoice.Customer.CustomerName.ToLower().Split(' ').Any(x => x.StartsWith(customer.ToLower())) ||
				invoice.Customer.CompanyName.ToLower().StartsWith(customer.ToLower())
				)
				&&
				productNames.All(productName => invoice.Products.Any(x => x.Name.ToLower().StartsWith(productName)))
				&&
				invoice.ToPay >= minValue && invoice.ToPay <= maxValue;
		}
	}
}